package com.hxzy.config.security;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.common.resp.R;
import com.hxzy.common.util.TokenService;
import com.hxzy.controller.login.resp.AdminLoginResp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


/**
 * 自定义用户退出操作
 */
@Component
public class JwtLogoutHandler implements LogoutSuccessHandler {

    @Autowired
    private TokenService tokenService;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        AdminLoginResp adminLoginUser = tokenService.getAdminLoginUser(request);

        if(adminLoginUser!=null){
            tokenService.delLoginUser(adminLoginUser.getToken());
        }

        try {
            request.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out=response.getWriter();

            int code = HttpStatus.OK.value();
            String msg = "用户退出成功";

            String json= JSONUtil.toJsonStr(R.okHasData(msg));
            out.println(json);
            out.flush();
            out.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
